package com.jksoft.darewayyyy.presenters;

import com.jksoft.darewayyyy.global.MyApplication;
import com.jksoft.darewayyyy.ui.IScanView;
import com.jksoft.darewayyyy.util.LogUtil;
import com.jksoft.darewayyyy.util.OkHttpClientManager;
import com.squareup.okhttp.Request;

import org.json.JSONException;
import org.json.JSONObject;

/**
 * Created by Administrator on 2015/11/9.
 */
public class ScanPresenter {
    private IScanView iScanView;
    public ScanPresenter(IScanView iScanView) {
        this.iScanView = iScanView;
    }

    public void checkByQrCode(String text) {
        iScanView.showLoading();
        try {
            LogUtil.e("ScanPresenter", "qrcodecontent" + text);
            JSONObject jsonObject = new JSONObject(text);
            OkHttpClientManager okHttpClientManager = OkHttpClientManager.getInstance();
            OkHttpClientManager.Param params[] = new OkHttpClientManager.Param[4];
            params[0] = new OkHttpClientManager.Param("id", jsonObject.getString("id"));
            params[1] = new OkHttpClientManager.Param("k", jsonObject.getString("k"));
            params[2] = new OkHttpClientManager.Param("type", "tablet");
            params[3] = new OkHttpClientManager.Param("pt", jsonObject.getString("pt"));
            okHttpClientManager.getPostDelegate().postAsyn(MyApplication.checkByQrcodeUrl, params, new OkHttpClientManager.ResultCallback<String>() {
                @Override
                public void onError(Request request, Exception e) {
                    iScanView.showError("什么破服务器，又没音了。");
                }

                @Override
                public void onResponse(String response) {
                    analysisData(response);
                }
            });
        } catch (JSONException e) {
            iScanView.showError("来人，将此人拿下！");
            e.printStackTrace();
        }
    }

    private void analysisData(String response) {

        try {
            LogUtil.e("ScanPresenter", response);
            JSONObject feedBack = new JSONObject(response);
            iScanView.hiddenLoading(feedBack.getString("errorCode"), feedBack.getString("errorText"));
        } catch (JSONException e) {
            iScanView.showError(e.getMessage());
            e.printStackTrace();
        }
    }
}
